package com.xy.weixin.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class RouteFilter
 */
public class RouteFilter implements Filter {

    /**
     * Default constructor. 
     */
    public RouteFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        
        res.setHeader("Cache-Control","no-cache");
        res.setHeader("Pragma","no-cache");
        res.setDateHeader ("Expires", -1);
        
        Boolean isGet = req.getMethod().equals("GET");
        System.out.println("isGet-->"+isGet);
        if (isGet) {
            doGet(req, res);
        } else {
            doPost(req, res);
        }
	}
	
	
	private void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		doGet(request, response);
    }

    private void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	String header = request.getHeader("user-agent");
        System.out.println("header:"+header);
        System.out.println(header.indexOf("Mozilla"));
        System.out.println(header.indexOf("Windows"));
    	if (header.indexOf("Mozilla") != -1) {
    		//PC浏览器
    		if(header.indexOf("Windows") != -1) {
    			response.sendRedirect("index.jsp");
    			//request.getRequestDispatcher("index.jsp").forward(request, response);
    		}else { //手机浏览器
    			response.sendRedirect("wap/index.jsp");
    			//request.getRequestDispatcher("wap/index.jsp").forward(request, response);
    		}
    	}else {
    		response.sendRedirect("index.jsp");
    		//request.getRequestDispatcher("index.jsp").forward(request, response);
    	}
    }
    
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
